import 'package:flutter/material.dart';

///实现状态保持,切换的时候,记住上一个页面的状态(例如列表记录的位置)
class KeepAliveWrapper extends StatefulWidget {
  final Widget child;
  final bool keepAlive;

  const KeepAliveWrapper({super.key,required this.child,this.keepAlive=true});

  @override
  State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;

  ///covariant关键字作用:
  ///重写父类方法时,可以指定参数为父类方法的参数的子类
  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    if(oldWidget.keepAlive !=widget.keepAlive) {
      updateKeepAlive();
    }
  }
}
